package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.User;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1. 校验参数
        if(null == dto || StringUtils.isEmpty(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        User user = AppThreadLocalUtil.getUser();
        if(null != user){
            apUserSearchService.insert(dto.getSearchWords(), user.getId());
        }


        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //2. 设置查询的条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //多字段查询
        boolQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR));

        if(null != dto.getMinBehotTime()){
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        }

        sourceBuilder.query(boolQuery);
        //3. 设置分页
        sourceBuilder.from(dto.getFromIndex());
        sourceBuilder.size(dto.getPageSize());
        //4. 设置排序
        sourceBuilder.sort("publishTime", SortOrder.DESC);

        //5. 设置高亮
        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("title");
        highlighter.preTags("<font style='color: red; font-size: inherit;'>");
        highlighter.postTags("</font>");
        sourceBuilder.highlighter(highlighter);
        //6. 查询
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //7. 结果的解析
        SearchHit[] hits = searchResponse.getHits().getHits(); // 返回命中的文档对象
        List<Map> list = new ArrayList<>(hits.length);

        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            //解析高亮数据
            if(null != highlightFields && highlightFields.size() > 0){
                HighlightField highlightField = highlightFields.get("title");
                Text[] fragments = highlightField.getFragments(); //获取到分段数据
                String h_title = StringUtils.join(fragments);
                map.put("h_title", h_title);
            }else {
                map.put("h_title", map.get("title"));
            }
            list.add(map);
        }

        //8. 返回结果
        return ResponseResult.okResult(list);
    }
}
